<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <el-input
          v-model="searchForm.title"
          placeholder="请输入职称"
          style="width: 200px;"
          class="filter-item"
        />
        <el-select
          v-model="searchForm.specialty"
          placeholder="专业领域"
          style="width: 200px;"
          clearable
          class="filter-item"
        >
          <el-option label="全部" value="" />
          <el-option label="个人成长" value="个人成长" />
          <el-option label="情感咨询" value="情感咨询" />
          <el-option label="学业压力" value="学业压力" />
        </el-select>
        <el-button 
          type="primary" 
          class="filter-item"
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button 
          class="filter-item"
          @click="handleReset"
        >
          重置
        </el-button>
      </div>

      <!-- 咨询师列表 -->
      <el-table
        v-loading="loading"
        :data="counselorList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column prop="realName" label="姓名" width="120" align="center" />
        <el-table-column prop="title" label="职称" width="120" align="center" />
        <el-table-column prop="specialty" label="专业领域" width="150" align="center" />
        <el-table-column prop="introduction" label="简介" min-width="200">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.introduction || '暂无简介'"
              placement="top-start"
            >
              <span class="truncate-text">{{ row.introduction || '暂无简介' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="qualification" label="资质" width="150" show-overflow-tooltip align="center" />
        <el-table-column prop="workYears" label="工作年限" width="100" align="center">
          <template #default="scope">
            {{ scope.row.workYears }}年
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" width="180" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              show-score
              :max="5"
              :score-template="scoreTemplate"
            />
          </template>
        </el-table-column>
        <el-table-column prop="consultationCount" label="咨询次数" width="100" align="center">
          <template #default="scope">
            {{ scope.row.consultationCount || 0 }}次
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="counselorList.length"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 咨询师详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="咨询师详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ currentCounselor.realName }}</el-descriptions-item>
        <el-descriptions-item label="职称">{{ currentCounselor.title }}</el-descriptions-item>
        <el-descriptions-item label="专业领域">{{ currentCounselor.specialty }}</el-descriptions-item>
        <el-descriptions-item label="从业年限">{{ currentCounselor.workYears || 0 }}年</el-descriptions-item>
        <el-descriptions-item label="评分">
          <el-rate
            v-model="currentCounselor.rating"
            disabled
            show-score
            :max="5"
          />
        </el-descriptions-item>
        <el-descriptions-item label="咨询次数">{{ currentCounselor.consultationCount || 0 }}次</el-descriptions-item>
        <el-descriptions-item label="资质证书" :span="2">{{ currentCounselor.qualification || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="个人简介" :span="2">
          <div class="introduction-text">{{ currentCounselor.introduction || '暂无简介' }}</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 证书图片 -->
      <div v-if="currentCounselor.certificateUrl" class="certificate-section">
        <h3>资质证书</h3>
        <template v-if="getFileType(currentCounselor.certificateUrl) === 'pdf'">
          <div class="pdf-preview" @click="handleCertificatePreview(currentCounselor.certificateUrl)">
            <el-icon class="pdf-icon"><Document /></el-icon>
            <span class="pdf-name">查看证书文件</span>
          </div>
        </template>
        <template v-else>
          <el-image
            :src="currentCounselor.certificateUrl"
            :preview-src-list="[currentCounselor.certificateUrl]"
            fit="contain"
            style="max-width: 100%; max-height: 300px"
          />
        </template>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑咨询师信息"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="专业领域" prop="specialty">
          <el-select
            v-model="editForm.specialty"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择专业领域"
            style="width: 100%"
          >
            <el-option
              v-for="item in specialtyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="从业年限" prop="workYears">
          <el-input-number v-model="editForm.workYears" :min="0" :max="50" />
        </el-form-item>
        <el-form-item label="资质证书" prop="certificateUrl">
          <div class="upload-box">
            <el-upload
              class="upload-certificate"
              action="/api/certificate"
              :headers="uploadHeaders"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :on-preview="handlePreview"
              accept=".jpg,.jpeg,.png,.pdf"
              :file-list="fileList"
            >
              <el-button type="primary" :icon="Upload">
                上传证书
              </el-button>
              <div class="upload-tip">
                支持jpg/jpeg/png/pdf格式，不超过10MB
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input
            v-model="editForm.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCounselorList, updateCounselor } from '@/api/counseling'
import { ElMessage } from 'element-plus'
import type { Counselor, CounselorQuery, PageResult } from '@/types/counseling'
import type { FormInstance } from 'element-plus'
import { Upload, Document } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'

interface SearchForm {
  title: string
  specialty: string
}

interface PageInfo {
  current: number
  size: number
  total: number
}

const router = useRouter()
const loading = ref(false)
const searchForm = ref<SearchForm>({
  title: '',
  specialty: ''
})

const page = ref<PageInfo>({
  current: 1,
  size: 10,
  total: 0
})

const counselorList = ref<Counselor[]>([])
const dialogVisible = ref(false)
const currentCounselor = ref<Counselor>({} as Counselor)

// 评分显示模板
const scoreTemplate = '{value}'

// 编辑相关
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref<Partial<Counselor>>({})

const editRules = {
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  title: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  specialty: [{ required: true, message: '请选择专业领域', trigger: 'change' }],
  workYears: [{ required: true, message: '请输入从业年限', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入个人简介', trigger: 'blur' }]
}

// 上传相关
const uploadHeaders = {
  Authorization: `Bearer ${getToken()}`
}

// 专业领域选项
const specialtyOptions = [
  { value: '心理咨询', label: '心理咨询' },
  { value: '职业规划', label: '职业规划' },
  { value: '情感咨询', label: '情感咨询' },
  { value: '学业问题', label: '学业问题' },
  { value: '人际关系', label: '人际关系' },
  { value: '家庭问题', label: '家庭问题' },
  { value: '压力管理', label: '压力管理' },
  { value: '自我认知', label: '自我认知' }
]

const fileList = ref<any[]>([])

// 获取咨询师列表
const loadCounselorList = async () => {
  loading.value = true
  try {
    const query: CounselorQuery = {
      pageNum: page.value.current,
      pageSize: page.value.size,
      title: searchForm.value.title,
      specialty: searchForm.value.specialty
    }
    const res = await getCounselorList(query)
    if (res.code === 200) {
      counselorList.value = res.data.records.map(item => ({
        ...item,
        rating: Number(item.rating) || 0
      }))
      page.value.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取咨询师列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  loadCounselorList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    title: '',
    specialty: ''
  }
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  page.value.size = val
  loadCounselorList()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  page.value.current = val
  loadCounselorList()
}

// 查看详情
const handleView = (row: Counselor) => {
  currentCounselor.value = { ...row }
  dialogVisible.value = true
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传jpg/jpeg/png/pdf格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response: any, file: any) => {
  if (response.code === 200) {
    editForm.value.certificateUrl = response.data
    fileList.value = [{ name: file.name, url: response.data }]
    ElMessage.success('证书上传成功')
  } else {
    ElMessage.error(response.message || '证书上传失败')
  }
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error('证书上传失败')
}

// 文件预览
const handlePreview = (file: any) => {
  const url = file.url.startsWith('/') ? file.url : '/' + file.url
  
  // 获取文件扩展名
  const extension = url.toLowerCase().split('.').pop()
  
  // 如果是图片，直接在新窗口打开
  if (['jpg', 'jpeg', 'png', 'gif'].includes(extension)) {
    window.open(url, '_blank')
  } else if (extension === 'pdf') {
    // 如果是PDF，使用浏览器的PDF预览功能
    const pdfUrl = `${window.location.origin}${url}`
    window.open(pdfUrl, '_blank')
  } else {
    // 其他类型的文件，提示下载
    ElMessage.info('此类型文件不支持预览，请下载后查看')
  }
}

// 编辑按钮点击
const handleEdit = (row: Counselor) => {
  editForm.value = { ...row }
  // 如果有证书URL，添加到文件列表
  if (row.certificateUrl) {
    fileList.value = [{
      name: '证书文件',
      url: row.certificateUrl
    }]
  } else {
    fileList.value = []
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateCounselor(editForm.value.id!, editForm.value)
        ElMessage.success('修改成功')
        editDialogVisible.value = false
        loadCounselorList()
      } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error('修改失败')
      }
    }
  })
}

// 获取文件类型
const getFileType = (url: string) => {
  const extension = url.toLowerCase().split('.').pop()
  return extension
}

// 添加证书预览方法
const handleCertificatePreview = (url: string) => {
  const fullUrl = url.startsWith('/') ? url : '/' + url
  const pdfUrl = `${window.location.origin}${fullUrl}`
  window.open(pdfUrl, '_blank')
}

onMounted(() => {
  loadCounselorList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
    .filter-item {
      margin-right: 10px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .certificate-section {
    margin-top: 20px;
    
    h3 {
      margin-bottom: 16px;
    }

    .pdf-preview {
      display: flex;
      align-items: center;
      padding: 16px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;
      background-color: #f5f7fa;

      &:hover {
        background-color: #e6e8eb;
      }

      .pdf-icon {
        font-size: 32px;
        color: #409eff;
        margin-right: 12px;
      }

      .pdf-name {
        color: #409eff;
        font-size: 14px;
      }
    }
  }

  .truncate-text {
    display: inline-block;
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .introduction-text {
    max-height: 100px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-all;
  }

  .upload-box {
    .upload-certificate {
      :deep(.el-upload-list) {
        margin-top: 8px;
      }
      
      :deep(.el-upload-list__item) {
        margin: 0;
        padding: 0;
        height: auto;
        
        .el-upload-list__item-name {
          padding: 0 30px 0 20px;
          line-height: 1.5;
          white-space: normal;
          word-break: break-all;
        }
       
        /* 去除'按 delete 键可删除'提示 */
        .el-icon-close-tip {
          display: none !important;
        }
      }
    }

    .upload-tip {
      margin-top: 8px;
      color: #909399;
      font-size: 12px;
    }
  }
}

:deep(.el-descriptions__body) {
  .el-descriptions__cell {
    padding: 12px !important;
  }
}

:deep(.el-dialog__body) {
  max-height: 80vh;
  overflow-y: auto;
}

.certificate-uploader,
.certificate-uploader-icon,
.certificate-image,
.certificate-tip {
  display: none;
}
</style> 